package com.ostrich.library_net

import androidx.lifecycle.LiveData
import retrofit2.CallAdapter
import retrofit2.Retrofit
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type

/**
 * @Author : yaotianxue
 * @Time : On 2023/10/24 10:02
 * @Description : LiveedataCallAdapterFactory
 */
class LivedataCallAdapterFactory: CallAdapter.Factory(){
    override fun get(
        returnType: Type,
        annotations: Array<out Annotation>,
        retrofit: Retrofit,
    ): CallAdapter<*, *>? {
        //获得最外面一层类型：判断是否为LiveData
        val rawType = getRawType(returnType)
        if(rawType != LiveData::class.java){
            throw IllegalArgumentException("must be LiveData")
        }
        //获得LiveData里面的第一个参数化类型:BaseResponse
        val parameterUpperBound = getParameterUpperBound(0, returnType as ParameterizedType)
        val rawType2 = getRawType(parameterUpperBound)
        if(rawType2  != BaseResponse::class.java){
            throw IllegalArgumentException("must be BaseResponse")
        }

        return LivedataCallAdapter<Any>(parameterUpperBound)





    }


    companion object{
        @JvmStatic
        fun create():LivedataCallAdapterFactory{
            return LivedataCallAdapterFactory()
        }
    }
}